#!/bin/bash

# 阿里云百炼平台curl示例
# 请将下面的API_KEY替换为您的实际API密钥
API_KEY="sk-416b931b781c420c9f6331b7346962b5"

# 设置API端点
UPLOAD_URL="https://dashscope.aliyuncs.com/compatible-mode/v1/files"
GENERATION_URL="https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"

# 文件路径
JSON_FILE="test_ingredients.json"

echo "步骤1: 上传JSON文件..."

# 上传文件并获取file-id
UPLOAD_RESPONSE=$(curl -s -w "%{http_code}" -X POST "$UPLOAD_URL" \
  -H "Authorization: Bearer $API_KEY" \
  --form "file=@$JSON_FILE" \
  --form "purpose=file-extract")

# 提取HTTP状态码和响应内容
HTTP_CODE=${UPLOAD_RESPONSE: -3}
RESPONSE_BODY=${UPLOAD_RESPONSE%???}

echo "HTTP状态码: $HTTP_CODE"
echo "响应内容: $RESPONSE_BODY"

# 检查上传是否成功
if [ "$HTTP_CODE" != "200" ]; then
    echo "文件上传失败"
    exit 1
fi

# 解析file-id
FILE_ID=$(echo "$RESPONSE_BODY" | jq -r '.id')

if [ "$FILE_ID" == "null" ] || [ -z "$FILE_ID" ]; then
    echo "无法解析file-id"
    exit 1
fi

echo "文件上传成功，file-id: $FILE_ID"

echo -e "\n步骤2: 调用qwen-doc-turbo模型..."

# 构造请求数据
REQUEST_DATA=$(cat <<EOF
{
  "model": "qwen-doc-turbo",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "you are a helpful assistant."
      },
      {
        "role": "system",
        "content": "fileid://$FILE_ID"
      },
      {
        "role": "user",
        "content": "菜品名称：西红柿炒鸡蛋 请根据提供的食材JSON数据，列出上面所需食材及食材所需克重配比。请严格按照JSON中的食材名称进行匹配并获取对应的ID。格式如：鸡蛋：150 西红柿：300 食用油：20 盐：3 白糖：5 葱花：5 水不用列出 请列出烹饪时长，以分钟为节点 如：时长：7 制作步骤： 1、热锅凉油，倒入蛋液，中火煎至底部凝固后翻炒成块，盛出备用 2、锅中补少许油，爆香蒜末/葱白，下西红柿翻炒至出汁 3、加入炒好的鸡蛋，加盐、糖调味，翻炒均匀，可加少量水略焖 4、撒葱花，淋少许生抽（可选），翻炒出锅"
      }
    ]
  },
  "parameters": {
    "enable_search": false,
    "incremental_output": false,
    "result_format": "message"
  }
}
EOF
)

# 调用模型
GENERATION_RESPONSE=$(curl -s -w "%{http_code}" -X POST "$GENERATION_URL" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Accept: application/json" \
  -d "$REQUEST_DATA")

# 提取HTTP状态码和响应内容
GEN_HTTP_CODE=${GENERATION_RESPONSE: -3}
GEN_RESPONSE_BODY=${GENERATION_RESPONSE%???}

echo "HTTP状态码: $GEN_HTTP_CODE"

if [ "$GEN_HTTP_CODE" != "200" ]; then
    echo "模型调用失败"
    echo "响应内容: $GEN_RESPONSE_BODY"
    exit 1
fi

# 解析模型返回内容
CONTENT=$(echo "$GEN_RESPONSE_BODY" | jq -r '.output.choices[0].message.content')

echo "模型调用成功:"
echo "$CONTENT"